/**
 * 
 */
package it.fuesi.myseries.api;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * @author pascotto
 *
 */
public class ApiClient {

	
	private static ApiClient client = null;
	
	private String endPoint;
	
	private ApiClient(String endPoint){
		this.endPoint = endPoint;
	}
	
	public static ApiClient getInstance(){
		if(client == null)
			client = new ApiClient("http://192.168.1.210:7070/MySeriesApi/rest"); //FIXME
		
		return client;
	}
	
	
	public static enum HTTPMethod{
		GET,
		PUT
	}
	
	public JSONObject callMethod(ApiMethod apiMethod, Map<String,String> queryParams) throws JSONException{
		final HttpParams httpParams = new BasicHttpParams();
	    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
	    HttpConnectionParams.setSoTimeout(httpParams, 5000);
	    
		final HttpClient httpClient = new DefaultHttpClient(httpParams);
		final HttpContext localContext = new BasicHttpContext();
		String url = endPoint + "/" + apiMethod.getContext().toString() + "/" + apiMethod.toString() + "?ts=" + System.currentTimeMillis();
		if(queryParams != null){
			for(Entry<String,String> entry : queryParams.entrySet()){
				try {
					url += "&" + entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		final HttpRequestBase request;
		if(apiMethod.getHTTPMethod() == HTTPMethod.PUT)
			request = new HttpPut(url);
		else
			request = new HttpGet(url);
		
		String responseText = null;
		JSONObject json = null;
		try {
			final HttpResponse response = httpClient.execute(request, localContext);
			HttpEntity entity = response.getEntity();
			responseText = getASCIIContentFromEntity(entity);
			json = new JSONObject(responseText);
		} catch (Exception e) {
			json = new JSONObject();
			json.put("success", false);
			json.put("error", e.getMessage());
		}
		
		return json;
		
	}
	
	private String getASCIIContentFromEntity(HttpEntity entity)
			throws IllegalStateException, IOException {
		InputStream in = entity.getContent();
		StringBuffer out = new StringBuffer();
		int n = 1;
		while (n > 0) {
			byte[] b = new byte[4096];
			n = in.read(b);
			if (n > 0)
				out.append(new String(b, 0, n));
		}
		return out.toString();
	}
	
}
